from django.db import models
from django.contrib.auth import get_user_model
from apps.books.models import Book

User = get_user_model()


class StockAlert(models.Model):
    """库存预警"""
    ALERT_TYPE_CHOICES = [
        ('low_stock', '库存不足'),
        ('out_of_stock', '缺货'),
        ('overstock', '库存过多'),
    ]

    book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name='stock_alerts')
    alert_type = models.CharField(max_length=20, choices=ALERT_TYPE_CHOICES, verbose_name='预警类型')
    threshold_quantity = models.IntegerField(verbose_name='预警阈值')
    current_quantity = models.IntegerField(verbose_name='当前库存')
    is_active = models.BooleanField(default=True, verbose_name='是否激活')
    message = models.TextField(blank=True, verbose_name='预警消息')
    
    # 通知设置
    notify_admin = models.BooleanField(default=True, verbose_name='通知管理员')
    notify_email = models.BooleanField(default=False, verbose_name='邮件通知')
    
    created_at = models.DateTimeField(auto_now_add=True)
    resolved_at = models.DateTimeField(null=True, blank=True, verbose_name='解决时间')

    class Meta:
        db_table = 'stock_alerts'
        verbose_name = '库存预警'
        verbose_name_plural = '库存预警'
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.book.title} - {self.get_alert_type_display()}"


class StockMovement(models.Model):
    """库存变动记录"""
    MOVEMENT_TYPE_CHOICES = [
        ('in', '入库'),
        ('out', '出库'),
        ('adjust', '调整'),
        ('return', '退货'),
        ('damage', '报损'),
    ]

    book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name='stock_movements')
    movement_type = models.CharField(max_length=20, choices=MOVEMENT_TYPE_CHOICES, verbose_name='变动类型')
    quantity = models.IntegerField(verbose_name='变动数量')
    previous_quantity = models.IntegerField(verbose_name='变动前数量')
    new_quantity = models.IntegerField(verbose_name='变动后数量')
    
    # 关联信息
    order = models.ForeignKey('orders.Order', on_delete=models.SET_NULL, null=True, blank=True, related_name='stock_movements')
    note = models.TextField(blank=True, verbose_name='备注')
    
    # 操作信息
    operator = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, related_name='stock_operations')
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = 'stock_movements'
        verbose_name = '库存变动'
        verbose_name_plural = '库存变动'
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.book.title} - {self.get_movement_type_display()} {self.quantity}"


class Supplier(models.Model):
    """供应商"""
    name = models.CharField(max_length=100, verbose_name='供应商名称')
    contact_person = models.CharField(max_length=50, blank=True, verbose_name='联系人')
    phone = models.CharField(max_length=20, blank=True, verbose_name='联系电话')
    email = models.EmailField(blank=True, verbose_name='邮箱')
    address = models.TextField(blank=True, verbose_name='地址')
    description = models.TextField(blank=True, verbose_name='描述')
    is_active = models.BooleanField(default=True, verbose_name='是否启用')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = 'suppliers'
        verbose_name = '供应商'
        verbose_name_plural = '供应商'
        ordering = ['name']

    def __str__(self):
        return self.name


class PurchaseOrder(models.Model):
    """采购订单"""
    STATUS_CHOICES = [
        ('draft', '草稿'),
        ('pending', '待确认'),
        ('confirmed', '已确认'),
        ('received', '已收货'),
        ('cancelled', '已取消'),
    ]

    order_number = models.CharField(max_length=32, unique=True, verbose_name='采购单号')
    supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE, related_name='purchase_orders')
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='draft', verbose_name='状态')
    
    # 金额信息
    total_amount = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='采购总金额')
    discount_amount = models.DecimalField(max_digits=10, decimal_places=2, default=0, verbose_name='优惠金额')
    final_amount = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='实付金额')
    
    # 时间信息
    expected_date = models.DateField(verbose_name='预期到货日期')
    received_at = models.DateTimeField(null=True, blank=True, verbose_name='实际到货时间')
    
    # 备注
    note = models.TextField(blank=True, verbose_name='备注')
    
    # 操作信息
    created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='created_purchase_orders')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = 'purchase_orders'
        verbose_name = '采购订单'
        verbose_name_plural = '采购订单'
        ordering = ['-created_at']

    def __str__(self):
        return self.order_number


class PurchaseOrderItem(models.Model):
    """采购订单明细"""
    purchase_order = models.ForeignKey(PurchaseOrder, on_delete=models.CASCADE, related_name='items')
    book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name='purchase_items')
    quantity = models.PositiveIntegerField(verbose_name='采购数量')
    unit_price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='单价')
    total_price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='小计金额')
    received_quantity = models.PositiveIntegerField(default=0, verbose_name='实收数量')
    
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = 'purchase_order_items'
        verbose_name = '采购订单明细'
        verbose_name_plural = '采购订单明细'

    def __str__(self):
        return f"{self.purchase_order.order_number} - {self.book.title}"


class GlobalStockSettings(models.Model):
    """全局库存设置"""
    low_stock_threshold = models.IntegerField(default=10, verbose_name='低库存预警阈值')
    out_of_stock_threshold = models.IntegerField(default=0, verbose_name='缺货预警阈值')
    overstock_threshold = models.IntegerField(default=1000, verbose_name='超储预警阈值')
    
    auto_alert_enabled = models.BooleanField(default=True, verbose_name='自动预警启用')
    alert_email_enabled = models.BooleanField(default=False, verbose_name='邮件通知启用')
    alert_admin_enabled = models.BooleanField(default=True, verbose_name='管理员通知启用')
    
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = 'global_stock_settings'
        verbose_name = '全局库存设置'
        verbose_name_plural = '全局库存设置'

    def __str__(self):
        return '全局库存设置'

    def save(self, *args, **kwargs):
        self.pk = 1  # 确保只有一条记录
        super().save(*args, **kwargs)

    @classmethod
    def get_settings(cls):
        settings, created = cls.objects.get_or_create(pk=1)
        return settings
